#pragma once
#include <iostream>
#include <string>
#include <sys/types.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/wait.h>
#include "../comm/util.hpp"
#include "../comm/log.hpp"

namespace ns_compiler
{
    using namespace ns_util;
    using namespace ns_log;
    class compiler
    {
    public:
        compiler()
        {
        }
        ~compiler()
        {
        }
        static bool compile(const std::string &filename)
        {
            pid_t pid = ::fork();
            if (pid < 0)
            {
                LOG(Level::ERROR) << "创建子进程失败" << "\n";
                return false;
            }
            else if (pid == 0)
            {
                umask(0);
                int _stderr = ::open(PathUtil::compileErr(filename).c_str(),
                                     O_CREAT | O_WRONLY, 0644);
                if (_stderr < 0)
                {
                    LOG(Level::WARNING) << "未生成stderr文件" << "\n";
                    exit(1);
                }
                // 重定向
                ::dup2(_stderr, 2);
                // 子进程进行编译
                // g++ -o myexe myprocess.cpp
                execlp("g++","g++", "-o", PathUtil::exe(filename).c_str(),
                       PathUtil::scr(filename).c_str(),"-D","COMPILER_ONLINE", nullptr);
                LOG(Level::ERROR) << "启动编译器g++失败，可能是参数错误" << "\n";
                exit(2);
            }
            else
            {
                // 父进程进行等待
                waitpid(pid, nullptr, 0);
                if (FileUtil::isFileExists(PathUtil::exe(filename)) && FileUtil::isFileEmptyBySize(PathUtil::compileErr(filename)))
                {
                    LOG(Level::INFO) << "编译成功" << '\n';
                    return true;
                }
                LOG(Level::ERROR) << "编译失败，没有形成可执行程序" << "\n";
                return false;
            }
        }
    };
}